from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.db import connection
from django.utils import timezone
import json

# Create your views here.

@require_POST
@csrf_exempt  # 在生产环境中应移除此装饰器并正确处理CSRF
def track(request):
    """接收并记录用户行为数据"""
    try:
        # 获取请求体中的JSON数据
        data = json.loads(request.body)
        
        # 获取用户IP
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip_address = x_forwarded_for.split(',')[0].strip()
        else:
            ip_address = request.META.get('REMOTE_ADDR')
        
        # 获取用户代理
        user_agent = request.META.get('HTTP_USER_AGENT', '')
        
        # 获取会话ID
        session_id = request.session.session_key
        if not session_id:
            request.session.create()
            session_id = request.session.session_key
        
        # 获取用户ID (如果已登录)
        user_id = request.user.user_id if request.user.is_authenticated else None
        
        # 获取事件类型和相关数据
        event_type = data.get('event_type', '')
        event_data = data.get('event_data', {})
        
        # 设置对象类型和ID
        object_type = event_data.get('object_type', None)
        object_id = event_data.get('object_id', None)
        
        # 获取URL和查询参数
        url = data.get('page_url', request.META.get('HTTP_REFERER', ''))
        query = data.get('query', None)
        
        # 将数据写入数据库
        with connection.cursor() as cursor:
            cursor.execute("""
                INSERT INTO tb_user_behavior
                (user_id, session_id, action_type, object_type, object_id, url, query, user_agent, ip_address, create_time)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            """, [
                user_id,
                session_id,
                event_type,
                object_type,
                object_id,
                url,
                query,
                user_agent,
                ip_address,
                timezone.now()
            ])
        
        return JsonResponse({'status': 'success'})
    
    except Exception as e:
        # 记录错误但不让前端知道具体错误
        print(f"Error tracking user behavior: {str(e)}")
        return JsonResponse({'status': 'error'}, status=500)
